package org.shiki.hrm.util.exception;

import org.shiki.hrm.util.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

/**
 *  全局异常处理
 * @author yang
 */
@RestControllerAdvice
public class HrmHandleException {
	/**
	 * 运行时异常处理
	 * @param e
	 * @return
	 */
	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public AjaxResult runtimeExceptionHandle(RuntimeException e){
		return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public AjaxResult runtimeExceptionHandle(MethodArgumentNotValidException e){
		// 封装校验未通过的字段
		BindingResult result = e.getBindingResult();
		List<FieldError> errors = result.getFieldErrors();
		// 封装结果
		HashMap<String, Object> map = new HashMap<>();
		errors.stream().forEach(error -> {
			map.put(error.getField(), error.getDefaultMessage());
		});
		return AjaxResult.me().setSuccess(false).setMessage(map.toString()).setErrorCode(HrmErrorCode.BUSINESS_ERROR);
	}

}
